package drexel.services;

import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.QueryParam;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;

import org.springframework.beans.factory.annotation.Autowired;

import drexel.model.W4FDOC;
import drexel.processors.RestEndpointMappingProcessor;

@Path("/movies")
public class RestService extends RestEndpointMappingProcessor {

	@Autowired
	private DBAccessService dbService = null;
	
	@GET
	@Path("/all")
	public List<W4FDOC> getAllMovies () {
		
		return listToMovies (dbService.getAllMovies ());
	}
	
	@GET
	@Path("/getMoviesByDirector")
	public List<W4FDOC> getAllMoviesByDirector (@QueryParam("director") String director) {
		
		System.out.println ("Director to search for: [" + director + "]");
		
		return listToMovies (dbService.getAllMoviesByDirector (director));
	}
	
	@GET
	@Path("/getMoviesByActor")
	public List<W4FDOC> getAllMoviesByActor (@QueryParam("actor") String actor) {
		
		System.out.println ("Actor to search for: [" + actor + "]");
		
		return listToMovies (dbService.getAllMoviesByActor (actor));
	}
	
	private List<W4FDOC> listToMovies (List<String> movies) {
		
		List<W4FDOC> out = new ArrayList<W4FDOC> ();
		
		try {
			
			if (movies != null && movies.size() > 0) {
				
				JAXBContext jaxbContext = JAXBContext.newInstance (W4FDOC.class);
				
				Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
				
				for (String xml : movies) {
					
					out.add ((W4FDOC) unmarshaller.unmarshal
						(
						new StringReader(xml)
						));
				}
			}
			
		} catch (JAXBException e) {

			e.printStackTrace();
		}
		
		return out;
	}
}
